package com.wyx.easyExcel.easyExcelHandler;


import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.wyx.easyExcel.easyExcelPojo.CellStyleWY;
import com.wyx.easyExcel.easyExcelPojo.PointXY;
import org.apache.poi.ss.usermodel.*;

import java.util.List;
import java.util.Map;

/**
 * https://blog.csdn.net/scholartang/article/details/108024953
 *
 * @date 01/22/2021 15:46
 */

/**
 * 处理order  模板的处理器你
 */
public class ExportAllFileCellColorHandler implements CellWriteHandler {


    /**
     * 单独的一种配置，第一个字段代表坐标，第二个代表样式
     */
    private Map<PointXY, CellStyleWY> maps;
    /**
     * 设个数据是啥意思呢，是为了保留之前的表格样式，所以需要克隆原先的样式，原先的样式在第几行，这个数据就是几  从0开始计算
     */
    private int Rows;


    public ExportAllFileCellColorHandler(Map<PointXY, CellStyleWY> maps) {
        this.maps = maps;
    }

    public void setRows(int rows) {
        Rows = rows;
    }

    public int getRows() {
        return Rows;
    }

    /**
     * 无参构造
     */
    public ExportAllFileCellColorHandler() {

    }

    /**
     * 可以设置每个单元格的样式。
     */
    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        int x = cell.getColumnIndex();
        int y = cell.getRowIndex();

        CellStyleWY cellStyleWY = maps.get(new PointXY(x, y));
        if (cellStyleWY == null) {
            return;
        }
        CellStyle cellStyle = writeSheetHolder.getSheet().getWorkbook().createCellStyle();
        //这一行是很关键的，getRow里面很重要，到底是克隆哪一行。
        cellStyle.cloneStyleFrom(writeSheetHolder.getCachedSheet().getRow(getRows()).getCell(x).getCellStyle());
        cellStyle.setFillForegroundColor(cellStyleWY.getColorIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        writeSheetHolder.getCachedSheet().getRow(y).createCell(x);
        Cell colorCell = writeSheetHolder.getCachedSheet().getRow(y).getCell(x);
        colorCell.setCellValue(cell.getStringCellValue());
        colorCell.setCellStyle(cellStyle);
    }
}